<?php

namespace App\Http\Controllers;

use App\Http\Requests\IndexDicRequest;
use App\Http\Requests\StoreDicRequest;
use App\Http\Requests\UpdateDicRequest;
use App\Http\Resources\DicResource;
use App\Models\Dic;
use App\Rules\CodeExistsRule;
use Illuminate\Support\Facades\Validator;

class DicController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth:sanctum');
    }

    /**
     * Display a listing of the resource.
     */
    public function index(IndexDicRequest $request, Dic $dic)
    {
        $this->authorize('viewAny', $dic);
        $name = $request->query('name');
        if ($name) {
            $dicData = $dic->where('name', 'like', '%' . $name . '%')->paginate(
                $request->query('pageSize'),
                ['*'],
                'page',
                $request->query('pageNum')
            );
            $dicData = DicResource::collection($dicData);
            return $this->success('查询成功', $dicData, $dicData->total());
        }
        $dicData =  DicResource::collection($dic->paginate(
            $request->query('pageSize'),
            ['*'],
            'page',
            $request->query('pageNum')
        ));
        return $this->success('查询成功', $dicData, $dicData->total());
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(StoreDicRequest $request, Dic $dic)
    {
        $this->authorize('create', $dic);
        Validator::make($request->input(), [
            'code' => [new CodeExistsRule()]
        ])->validate();
        $dic->fill($request->input());
        $dic->save();
        return $this->success('新增成功', $dic);
    }

    /**
     * Display the specified resource.
     */
    public function show(Dic $dic)
    {
        $this->authorize('viewAny', $dic);
        return $this->success('查询成功', new DicResource($dic));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Dic $dic)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(UpdateDicRequest $request, Dic $dic)
    {
        //
        $this->authorize('update', $dic);
        $exists = Dic::where('code', $request->input('code'))
            ->whereNot('id', $dic->id) // 排除当前记录
            ->exists();
        if ($exists) {
            return $this->error('value 已经存在，无法新增重复的 value');
        }
        $dic->fill($request->input());
        $dic->save();
        return $this->success('更新成功', $dic);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Dic $dic)
    {
        $this->authorize('delete', $dic);
        $dic->delete();
        return $this->success('删除成功', new DicResource($dic));
    }
}
